/**
 * 暂不进行优先级排序
 * 优先级采用堆
 * Created by Administrator on 2017/5/12.
 */
var redbag = require('../models/RedBag')
var async = require('async');

bagpipe = {
    isRunning: false,
    qworks: [],
    enQueue: function (obj) {
        //{key:openid,callback:func}
        this.qworks.push(obj);
        if (!this.isRunning) {
            this.start();
        }
    },
    deQueue: function () {
        this.qworks.shift()
    },
    getFirst: function () {
        return this.qworks[0]
    },
    getLast: function () {
        return this.qworks[this.qworks.length - 1];
    },
    next: function () {

        if(!this.isRunning||this.qworks.length==0){
            return;
        }


        var that = this;

        var item = that.getFirst();
        if (that.qworks.length > 0 && item) {



            // item.callback('pipe+' + item.key);
            // that.deQueue();
            //
            //
            // if(that.qworks.length>0) {
            //     that.next();
            // }else{
            //     that.isRunning=false;
            // }

            // that.deQueue();
            // setTimeout(function () {
            //
            //     item.callback('pipe+' + item.key);
            //
            //     if(that.qworks.length>0&&that.isRunning) {
            //         that.next();
            //     }else{
            //         that.isRunning=false;
            //     }
            // },1000)

            that.deQueue();
            redbag.getRedBag(item.isUser,item.key, function (result) {

                item.callback(result);
                if (that.qworks.length > 0) {
                    that.next();
                } else {
                    that.isRunning = false;
                }
            })
        }
    },
    start: function () {
        var that=this;
        setInterval(function () {
            // console.log('start    pipe')
            if((!that.isRunning)&&that.qworks.length>0) {
                console.log('start    pipe   start next')

                that.isRunning = true;
                that.next();
            }
        },3000)
        // while (true) {

        // }
    },
    getRedBag:function (key, callback) {
        redbag.getRedBag(key,function (reslut) {
            callback(reslut);
        })
    }

}


// bagpipe.on()
module.exports = bagpipe;